package com.sskj.b70.v.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.sskj.b70.MyAppLication;
import com.sskj.b70.R;
import com.sskj.b70.common.App;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.widget.ToolBarLayout;
import com.sskj.b70.p.base.BasePresenter;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.SPUtils;
import com.sskj.b70.utils.ToastUtil;
import com.sskj.b70.v.base.BaseActivity;
import com.takwolf.android.lock9.Lock9View;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;
import zwh.com.lib.FPerException;
import zwh.com.lib.IdentificationInfo;
import zwh.com.lib.RxFingerPrinter;

/**
 * 作者 :吕志豪
 * 简书：https://www.jianshu.com/u/6e525b929aac
 * github：https://github.com/lvzhihao100
 * 描述：
 * 创建时间：2018-08-17 09:08
 */
public class LockActivity extends BaseActivity<BasePresenter> {
    private static final int LEAST_NODE = 6;
    @BindView(R.id.lock9View)
    Lock9View lock9View;
    @BindView(R.id.tvAccount)
    TextView tvAccount;
    @BindView(R.id.btChange)
    Button btChange;
    @BindView(R.id.toolBar)
    ToolBarLayout toolBar;
    private boolean isFirst;
    private int[] firstNum;
    private int errorTime = 0;
    private static final int ERROR_ALL_TIME = 5;
    private boolean isSet = false;
    private boolean isUpdate = false;

    public static void start(Activity context) {
        Intent starter = new Intent(context, LockActivity.class);
        starter.putExtra(Constants.IS_SET, true);
        context.startActivityForResult(starter, Constants.ACTIVITY_LOCK);

    }

    public static void check(Context context) {
        Intent starter = new Intent(context, LockActivity.class);
        context.startActivity(starter);
    }

    public static void update(Activity context) {
        Intent starter = new Intent(context, LockActivity.class);
        starter.putExtra(Constants.IS_UPDATE, true);
        context.startActivityForResult(starter, Constants.ACTIVITY_LOCK);

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_lock;
    }

    @Override
    public BasePresenter getPresenter() {
        return new BasePresenter();
    }

    @Override
    protected void initView() {

        isFirst = true;
        isSet = getIntent().getBooleanExtra(Constants.IS_SET, false);
        isUpdate = getIntent().getBooleanExtra(Constants.IS_UPDATE, false);
        toolBar.setLeftButtonOnClickLinster((v) -> {
            onBackPressed();
        });
        if (isUpdate) {
            toolBar.setVisibility(View.VISIBLE);
            updatePwd();
        } else {
            if (!isSet) {
                checkPwd();
                toolBar.setVisibility(View.GONE);
//            setFinger();
            } else {
                toolBar.setVisibility(View.VISIBLE);

                setPwd();
            }
        }

    }

    private void updatePwd() {
        checkPwd();
    }

    /**
     * 设置密码
     */
    private void setPwd() {
        tvAccount.setText(App.INSTANCE.getString(R.string.strLockActivity3));
        btChange.setVisibility(View.GONE);
        lock9View.setGestureCallback(new Lock9View.GestureCallback() {
            @Override
            public void onNodeConnected(@NonNull int[] numbers) {
                System.out.println(numbers);
            }

            @Override
            public void onGestureFinished(@NonNull int[] numbers) {
                if (isFirst) {
                    if (numbers.length < LEAST_NODE) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strLockActivity4));
                        return;
                    }
                }
                if (isFirst) {
                    isFirst = false;
                    firstNum = numbers;
                    tvAccount.setText(App.INSTANCE.getString(R.string.strLockActivity5));
                } else {
                    if (firstNum.length != numbers.length) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strLockActivity6));
                        return;
                    }
                    boolean isSame = true;
                    String number = "";
                    for (int i = 0; i < firstNum.length; i++) {
                        number = number + " " + firstNum[i];
                        if (firstNum[i] != numbers[i]) {
                            isSame = false;
                            break;
                        }
                    }
                    number = number.replaceFirst(" ", "");
                    if (!isSame) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strLockActivity11));
                        return;
                    }
                    SPUtils.put(Constants.GESTURE_PASSWD, number, MyAppLication.getID());
                    SPUtils.put(Constants.IS_GESTURE_SET, true, MyAppLication.getID());
                    SPUtils.put(Constants.IS_GESTURE_ON, true, MyAppLication.getID());
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLockActivity12));
                    setResult(Constants.GESTURE_PASSWD_OK);
                    finish();
                }
            }
        });
    }

    /**
     * 验证密码,禁掉返回按键
     */
    private void checkPwd() {
        if (MyAppLication.isLogin()) {
            if (!TextUtils.isEmpty(MyAppLication.getMobile())) {
                String mobile = MyAppLication.getMobile();
                String text = mobile.substring(0, 3) + "****" + mobile.substring(7, 11);
                tvAccount.setText(text);
            } else {
                tvAccount.setText(MyAppLication.getEmail());
            }
        }
        ClickUtil.click(btChange, () -> {
            MyAppLication.IS_FIRST_LOCK = true;
            MyAppLication.getApplication().logout();
        });
        lock9View.setGestureCallback(new Lock9View.GestureCallback() {
            @Override
            public void onNodeConnected(@NonNull int[] numbers) {
                System.out.println(numbers);
            }

            @Override
            public void onGestureFinished(@NonNull int[] numbers) {
                String number = (String) SPUtils.get(Constants.GESTURE_PASSWD, "", MyAppLication.getID());
                String[] split = number.split(" ");
                if (split.length != numbers.length) {
                    judgeExit();
                    return;
                }
                boolean isSame = true;
                for (int i = 0; i < split.length; i++) {
                    if (Integer.valueOf(split[i]) != numbers[i]) {
                        isSame = false;
                        break;
                    }
                }
                if (!isSame) {
                    judgeExit();
                } else {
                    if (isUpdate) {
                        setPwd();
                    } else {
                        finish();
                    }
                }
            }
        });
    }

    private void setFinger() {
        RxFingerPrinter rxFingerPrinter = new RxFingerPrinter(this);
        DisposableObserver<IdentificationInfo> observer =
                new DisposableObserver<IdentificationInfo>() {
                    @Override
                    protected void onStart() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onNext(IdentificationInfo info) {
                        if (info.isSuccessful()) {
                            //指纹验证成功
                            ToastUtil.showShort(App.INSTANCE.getString(R.string.strLockActivity13));
                            finish();

                        } else {
                            //指纹验证失败
                            FPerException exception = info.getException();
                            ToastUtil.showShort(exception.getDisplayMessage());
                        }

                    }
                };
        rxFingerPrinter.begin().subscribe(observer);//RxfingerPrinter会自动在onPause()时暂停指纹监听，onResume()时恢复指纹监听)
    }

    private void judgeExit() {
        errorTime++;
        if (errorTime < ERROR_ALL_TIME) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strLockActivity14) + (ERROR_ALL_TIME - errorTime) + App.INSTANCE.getString(R.string.strLockActivity15));
        } else {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strLockActivity16));
            MyAppLication.IS_FIRST_LOCK = true;
            SPUtils.clear(MyAppLication.getID());
            MyAppLication.getApplication().logout();
        }
    }


    @Override
    public void onBackPressed() {
        if (isSet || isUpdate) {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
